<template>
  <div class="audio-player">
    <el-button
      :type="isPlaying ? 'danger' : 'primary'"
      size="small"
      :loading="loading"
      @click="togglePlay"
    >
      <el-icon>
        <component :is="isPlaying ? VideoPause : VideoPlay" />
      </el-icon>
      {{ isPlaying ? "暂停" : "播放" }}
    </el-button>

    <div v-if="showProgress && duration > 0" class="progress-info">
      <span class="time"
        >{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span
      >
      <el-progress
        :percentage="progressPercentage"
        :show-text="false"
        :stroke-width="4"
        style="width: 100px; margin-left: 8px"
      />
    </div>


    <audio
      ref="audioRef"
      :src="fullAudioUrl"
      @loadstart="loading = true"
      @loadeddata="onLoadedData"
      @timeupdate="onTimeUpdate"
      @ended="onEnded"
      @error="onError"
      preload="metadata"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted, onMounted } from "vue";
import { ElButton, ElIcon, ElProgress } from "element-plus";
import { VideoPlay, VideoPause } from "@element-plus/icons-vue";
import { useMessage } from "@/hooks/useMessage";
import { getFullFileUrl } from "@/utils/fileUrl";
import { useAudioManager } from "../composables/useAudioManager";

interface Props {
  audioUrl: string;
  fileName?: string;
  showProgress?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  fileName: "音频文件",
  showProgress: false,
});

// 计算完整的音频URL
const fullAudioUrl = computed(() => {
  const url = getFullFileUrl(props.audioUrl);
  // console.log("原始音频路径:", props.audioUrl);
  // console.log("完整音频URL:", url);
  return url;
});

const msg = useMessage();
const audioManager = useAudioManager();

// 生成唯一的组件实例ID
const instanceId = ref(`audio-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);

const audioRef = ref<HTMLAudioElement>();
const isPlaying = ref(false);
const loading = ref(false);
const currentTime = ref(0);
const duration = ref(0);

const progressPercentage = computed(() => {
  if (duration.value === 0) return 0;
  return Math.round((currentTime.value / duration.value) * 100);
});

const togglePlay = async () => {
  if (!audioRef.value) return;

  try {
    if (isPlaying.value) {
      audioRef.value.pause();
      isPlaying.value = false;
      audioManager.unregisterAudioPlay(instanceId.value);
    } else {
      // 注册当前音频播放（会自动暂停其他音频）
      audioManager.registerAudioPlay(audioRef.value, instanceId.value);
      await audioRef.value.play();
      isPlaying.value = true;
    }
  } catch (error) {
    console.error("播放失败:", error);
    console.error("音频URL:", fullAudioUrl.value);
    console.error("错误详情:", error);
    msg.error(
      `播放失败: ${error instanceof Error ? error.message : "未知错误"}`
    );
    loading.value = false;
    isPlaying.value = false;
    audioManager.unregisterAudioPlay(instanceId.value);
  }
};

const onLoadedData = () => {
  loading.value = false;
  if (audioRef.value) {
    duration.value = audioRef.value.duration || 0;
  }
};

const onTimeUpdate = () => {
  if (audioRef.value) {
    currentTime.value = audioRef.value.currentTime;
  }
};

const onEnded = () => {
  isPlaying.value = false;
  currentTime.value = 0;
  audioManager.unregisterAudioPlay(instanceId.value);
};

const onError = (event: Event) => {
  loading.value = false;
  isPlaying.value = false;
  console.error("音频加载失败:", event);
  console.error("音频URL:", fullAudioUrl.value);
  msg.error(`音频加载失败: ${props.fileName}`);
  audioManager.unregisterAudioPlay(instanceId.value);
};

const formatTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};


// 监听其他音频播放，自动暂停当前音频
onMounted(() => {
  // 监听音频元素的pause事件，当被其他音频暂停时更新状态
  if (audioRef.value) {
    audioRef.value.addEventListener('pause', () => {
      if (!audioManager.isCurrentPlaying(instanceId.value)) {
        isPlaying.value = false;
      }
    });
  }
});

// 组件卸载时停止播放并取消注册
onUnmounted(() => {
  if (audioRef.value && isPlaying.value) {
    audioRef.value.pause();
  }
  audioManager.unregisterAudioPlay(instanceId.value);
});
</script>

<style scoped>
.audio-player {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-info {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.time {
  white-space: nowrap;
  font-size: 11px;
}
</style>
